package com.ruipengkj.component.jtable;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.TexturePaint;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;

import com.ruipengkj.commons.util.Util;
import com.ruipengkj.factory.ImageFactory;

public class RPTableHeaderRenderer extends JLabel implements TableCellRenderer {
	private static final long serialVersionUID = 1L;
	private Color background = Util.TABLE_HEADER_BACKGROUND_COLOR;
    private Color textColor = Color.BLACK;
    private Color borderLightColor = Util.TABLE_HEADER_BORDER_BRIGHT_COLOR;
    private Color borderDarkColor = Util.TABLE_HEADER_BORDER_DARK_COLOR;
    private int tableHeaderHeight = 36;
    private ImageIcon backgroundImageIcon = ImageFactory.loadImage(ImageFactory.TABLE_HEADER_BG);
	private TexturePaint paint = Util.createTexturePaint(backgroundImageIcon.getImage());
	
	public RPTableHeaderRenderer(){
//		setContentAreaFilled(false); // 这一句非常重要, 否则父类还会绘制按钮的区域
//		setOpaque(false);
//		setFocusPainted(false);
//		setBorderPainted(false);
	}
	
    private Border border = new Border() {
		public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            g.setColor(borderDarkColor);
            g.drawRect(x, y, width - 1, height - 1);
            //draw brigher border.
            g.setColor(borderLightColor);
            g.drawLine(x, y, x, height - 1);
        }

        public Insets getBorderInsets(Component c) {
            return new Insets(1,Util.TABLE_CELL_LEADING_SPACE, 1, 1);
        }

        public boolean isBorderOpaque() {
            return true;
        }
    };

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
//        super.getTableCellRendererComponent(table,
//                value, isSelected, hasFocus, row, column);

        this.setFont(Util.TABLE_HEADER_FONT);
        this.setBackground(background);
        this.setForeground(textColor);
        this.setBorder(border);
        this.setText(value.toString());
        this.setHorizontalTextPosition(JLabel.CENTER);
        return this;
    }
    
    @Override
	protected void paintComponent(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		g2d.setPaint(paint);
		g2d.fillRect(0, -1, this.getWidth(), this.getHeight());
		super.paintComponent(g);
	}
    @Override
    public Dimension getPreferredSize() {
        Dimension size = super.getPreferredSize();
        return new Dimension(size.width, tableHeaderHeight);
    }
}
